import path from 'path'
import fs from 'fs'
import archiver from 'archiver'
import chalk from 'chalk'
import { projectPathsFn } from './constant.js'

async function compress(outputDir, answers) {
    console.log(chalk.green('开始进行压缩~~~'))
    const { dirPath, apply } = answers
    // 获取选择打包的项目路径
    const projectPaths = projectPathsFn(dirPath, apply)
    const packageDirs = Object.keys(projectPaths)
    // 压缩输出文件夹
    const outputZipPath = path.join(outputDir, 'output.zip')
    const outputZipStream = fs.createWriteStream(outputZipPath)
    const archive = archiver('zip', { zlib: { level: 9 } })
    archive.pipe(outputZipStream)
    packageDirs.forEach((packageDir) => {
        archive.directory(path.join(projectPaths[packageDir], packageDir), packageDir)
    });
    archive.finalize();

    outputZipStream.on('close', () => {
        console.log(chalk.green(`压缩完成，请在${outputDir}目录下查看`))
    });

    outputZipStream.on('error', (error) => {
        console.error(chalk.red(`压缩文件时出错：${error.message}`))
        process.exit(1);
    })
}
export default compress;